#! /usr/bin/python
# -*- coding: cp1250 -*-

import os
import psycopg2

class Pg:
    """ """
    def __init__(self):
        self.server = '127.0.0.1'
        self.database = 'work'
        self.user = 'postgres'

        self.error = ''
        self.debug_mode = False

    def connect(self):
        constr = "dbname='%s' user='%s' host='%s'" % (self.database, self.user, self.server)

        self.con = psycopg2.connect(constr)
        #self.con = psycopg2.connect("dbname='wrk2' user='postgres' host='127.0.0.1'")
        #try:
        #    self.con = psycopg2.connect("dbname='work' user='postgres' host='localhost' password='xxx'");
        #    self.con = psycopg2.connect("dbname='work' user='postgres' host='localhost'");
        #except:
        #    self.error = "I am unable to connect to the database"

        self.cur = self.con.cursor()

    def query(self, query):
        #ce_type = 'win1250'
        #if os.name == 'posix': ce_type = 'UTF-8'
        #ce = "SET client_encoding TO '%s';\n" % (ce_type)
        #of = open('/rdisk/test.txt', 'w')
        #of.write(ce + query)
        #of.close()

        #self.cur.execute(ce + query)
        if self.debug_mode == True:
            print "-", query, "-"

        self.cur.execute(query)
        self.con.commit()
        
    def __getitem__(self, index):
        row = self.cur.fetchone()
        if row:
            return row
        else:
            raise IndexError

if __name__ == "__main__":
    """ http://www.postgresql.org/files/documentation/books/aw_pgsql/node183.html
    """
    p = Pg()
    p.connect()

    #p.debug_mode = True

    #p.query('select * from pg_tables')
    p.query('select * from pg_database')
    #p.query('select * from pg_class')

    for r in p:
        print r[0], r
